
package uestc.bitman.edxapp.tools;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;

public class VideoDownloadTools {

    public static String generateStringMD5(String str) {
        
        byte[] hash = null;
        try {
            hash = MessageDigest.getInstance("MD5").digest(str.getBytes("UTF-8"));
            StringBuilder hex = new StringBuilder(hash.length * 2);
            for (byte b : hash) {
                if ((b & 0xff) < 0x10) {
                    hex.append("0");
                }
                hex.append(Integer.toHexString(b & 0xff));
            }
            return hex.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    public static String generateHashFileName(String courseName, String chapterName,
            String sectionName, String videoTitle) {
        return generateStringMD5(courseName + "_" + chapterName + "_" + sectionName + "_"
                + videoTitle);
    }

    public static InputStream getInputStreamFromUrl(String urlStr) {
        InputStream inputStream = null;
        URL url;
        try {
            url = new URL(urlStr);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            inputStream = connection.getInputStream();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    public static File writeToSDCard(String path, String fileName, InputStream inputStream) {
        File file = null;
        OutputStream os = null;
        try {
            file = new File(path + fileName);
            os = new FileOutputStream(file);
            byte buffer[] = new byte[1024];
            while ((inputStream.read(buffer)) != -1) {
                os.write(buffer);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    public static boolean urlDownloadToFile(final String url, final String path,
            final String fileName) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                InputStream is = getInputStreamFromUrl(url);
                writeToSDCard(path, fileName, is);
            }
        };
        Thread th = new Thread(runnable);
        th.start();
        return true;
    }
}
